package com.jtpay.sdk.util;

import android.app.Activity;
import android.content.Intent;

import com.jtpay.sdk.activity.PayResultsActivity;

import java.util.ArrayList;
import java.util.List;

import sdk.pay.PayUtil;
import sdk.pay.listener.PayGetPayStatusListener;
import sdk.pay.listener.PayUtilCallBack;
import sdk.pay.model.TokenParam;

/**
 * Created by Administrator on 2017/8/22.
 */

public class PayUtilHelper implements PayGetPayStatusListener, PayUtilCallBack {
    private List<Observer> mObservers = new ArrayList<>();
    private PayUtil mPayUtil;
    private Activity mActivity;

    private PayUtilHelper() {
    }

    public static PayUtilHelper getInstance() {
        return Holder.helper;
    }

    @Override
    public void onPayStatus(int payStatus) {
        AuthUtil.getInstance().resetTest();
        Intent intent = new Intent(mActivity, PayResultsActivity.class);
        intent.putExtra("payStatus", payStatus);
        mActivity.startActivity(intent);
    }

    @Override
    public void onPayException(String exceptionMsg) {
        notifyObserversIN();
    }

    public void init(Activity activity) {
        mActivity = activity;
        if (mPayUtil == null) {
            mPayUtil = new PayUtil(activity, this, true);
        }
    }

    public void setParams(String... params) {
        if (mPayUtil != null && params != null && params.length > 0) {
            mPayUtil.setPayParam(params);
        }
    }

    public void pay(String typeId, TokenParam tokenParam) {
        if (mPayUtil != null)
            mPayUtil.pay(typeId, tokenParam);
    }

    public void getPayStatus() {
        if (mPayUtil != null) {
            mPayUtil.getPayStatus(this);
        }
    }

    /**
     * 添加观察者
     *
     * @param observer
     * @return
     */
    public boolean attachObserver(Observer observer) {
        return !mObservers.contains(observer) && mObservers.add(observer);
    }

    /**
     * 删除观察者
     *
     * @param observer
     * @return
     */
    public boolean detachObserver(Observer observer) {
        return mObservers.contains(observer) && mObservers.remove(observer);
    }

    /**
     * 通知观察者
     */
    private void notifyObserversIN() {
        for (Observer observer : mObservers) {
            observer.onChangeCallBack();
        }
    }

    public interface Observer {
        void onChangeCallBack();
    }

    private static final class Holder {
        private static final PayUtilHelper helper = new PayUtilHelper();
    }

}
